import csv

import tablib
from django.http import HttpResponse, FileResponse
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from rest_framework.views import APIView
from rest_framework import permissions
from utils.custom_json_response import JsonResponse
from django_filters.rest_framework import DjangoFilterBackend
from utils.custom_api_view import ListCreateAPIView, DetailApiView, DeleteApiView
import time
from .models import Customer
from .serializers import CustomerSerializer
from rest_framework import filters
from .filter import CustomerFilter
from .resource import CustomerImportResource, CustomerExportResource
from import_export.results import Error


class SystemStatusApiView(APIView):
    """
    检查系统状态：

    http://127.0.0.1:8000/api/v1/module/status/
    """

    permission_classes = [permissions.AllowAny, ]

    throttle_class = (AnonRateThrottle, UserRateThrottle)

    def get(self, request, *args, **kwargs):
        data = {
            "当前时间": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            "test": "success"
        }
        return JsonResponse(msg="success", code=200, data=data)


class CustomerListApiView(ListCreateAPIView):
    """
    客户信息

    get:
        获取客户信息列表

    post:
        创建客户信息
    """

    # 访问权限
    permission_classes = [permissions.AllowAny, ]

    # 过滤，设置固定字段
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    filter_class = CustomerFilter

    # 排序
    queryset = Customer.objects.all()

    # 排序
    ordering_fields = ["id", ]  # 可排序字段
    ordering = ('-id',)  # 默认排序

    # 序列化
    serializer_class = CustomerSerializer

    # 模型
    model = Customer


class CustomerDeleteApiView(DeleteApiView):
    """
    批量删除客户信息
    """

    # 访问权限
    permission_classes = [permissions.AllowAny, ]

    model = Customer


class CustomerDetailApiView(DetailApiView):
    """
    客户列表详情序列化视图

    get:
        获取单条客户数据信息

    put:
        编辑客户信息

    delete:
        客户信息单条记录删除
    """

    # 访问权限
    permission_classes = [permissions.AllowAny, ]

    # 序列化
    serializer_class = CustomerSerializer

    # 模型
    model = Customer


class ImportApiView(APIView):
    """
    port:
        批量导入客户信息

    get:
        批量导出客户信息
    """

    # 只有认证登录后，才能访问
    permission_classes = [permissions.AllowAny, ]

    def post(self, request, *args, **kwargs):
        if "file" not in request.data or not request.data["file"]:
            return JsonResponse(msg="请上传文件", code=400)

        file = request.data["file"]  # 接收前端传过来的文件参数
        dataset = tablib.Dataset().load(file.read())  # 将数据加载到 tablib 表格数据集
        resource = CustomerImportResource()  # 获取导入数据格式

        # dry_run=True，表示测试当前数据导入，并获取结果对象
        result = resource.import_data(dataset, dry_run=True)

        # 获取数据格式是否有错误，返回bool值：True 为有错误，Fasle为没有错误
        if result.has_errors():
            return JsonResponse(msg="数据格式错误", code=400)

        # 获取数据是否有错误，返回bool值：True 为有错误，Fasle为没有错误
        if result.has_validation_errors():
            invalid_rows = len(result.invalid_rows)
            return JsonResponse(msg=f"一共有{invalid_rows}行异常数据，请检查！", code=400)

        # 真正导入数据
        success_result = resource.import_data(dataset, dry_run=False)

        new = success_result.totals.get('new')
        update = success_result.totals.get('update')
        skip = success_result.totals.get('skip')

        return JsonResponse(msg=f"导入数据成功，新增{new}条数据，更新{update}条数据，跳过{skip}条数据", code=200)

    def get(self, request, *args, **kwargs):

        # 导出数据
        dataset = CustomerExportResource().export()

        # 返回数据到前端
        response = HttpResponse(content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        response['Content-Disposition'] = 'attachment;filename=customer.xlsx'
        response.write(dataset.xlsx)

        return response